package com.sky.controller;

import com.sky.domain.WmsWareSku;
import com.sky.dto.SkuStockVO;
import com.sky.exception.BizCodeEnum;
import com.sky.service.WmsWareSkuService;
import com.sky.to.member.MemberReceiveAddressTo;
import com.sky.to.ware.StockTo;
import com.sky.utils.PageUtils;
import com.sky.utils.R;
import com.sky.vo.param.WareSkuVO;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/wareSku")
public class WmsWareSkuController {

    @Resource
    private WmsWareSkuService wareSkuService;

    @GetMapping("/page")
    public R page(WareSkuVO vo) {
        PageUtils pageUtils = wareSkuService.pageQuery(vo);
        return R.ok(pageUtils);
    }

    @GetMapping("/getById/{id}")
    public R getById(@PathVariable("id") Long id) {
        return R.ok(wareSkuService.getById(id));
    }

    @PostMapping("/save")
    public R save(@RequestBody WareSkuVO vo) {
        WmsWareSku wareSku = new WmsWareSku();
        BeanUtils.copyProperties(vo, wareSku);
        return wareSkuService.save(wareSku) ? R.ok() : R.error();
    }

    @PostMapping("/update")
    public R update(@RequestBody WareSkuVO vo) {
        WmsWareSku wareSku = new WmsWareSku();
        BeanUtils.copyProperties(vo, wareSku);
        return wareSkuService.updateById(wareSku) ? R.ok() : R.error();
    }

    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable("id") Long[] id) {
        return R.ok(wareSkuService.removeBatchByIds(Arrays.asList(id)));
    }

    /**
     * 批量查询商品库存情况
     **/
    @PostMapping("/getSkuStock")
    public R<List<SkuStockVO>> getSkuStock(@RequestBody List<Long> skuIds) {
        return R.ok(wareSkuService.getSkuStock(skuIds));
    }

    /**
     * 根据收货地址id计算运费
     **/
    @GetMapping("/getFreight")
    public R<MemberReceiveAddressTo> getFreight(@RequestParam("addrId")Long addrId) throws Exception{
        return R.ok(wareSkuService.getFreight(addrId));
    }

    /**
     * 生成订单锁库存
     **/
    @PostMapping("/lockStock")
    public R<Boolean> lockStock(@RequestBody StockTo stockTo){
        Boolean stock;
        try {
            stock = wareSkuService.lockStock(stockTo);
        } catch (Exception e) {
            return R.error(BizCodeEnum.SKU_STOCK_EXCEPTION.getCode(), BizCodeEnum.SKU_STOCK_EXCEPTION.getMsg());
        }
        if (!stock) {
            return R.error(BizCodeEnum.SKU_STOCK_EXCEPTION.getCode(), BizCodeEnum.SKU_STOCK_EXCEPTION.getMsg());
        }
        return R.ok();
    }
}
